<template>
    <div>
      <el-card>
        <template #header>
          <h2>退住登记</h2>
        </template>
        <!-- 搜索区域 -->
        <el-form :model="searchForm" inline>
          <el-form-item>
            <el-input
              v-model="searchForm.name"
              placeholder="客户姓名"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchData">查询</el-button>
            <el-button type="primary" @click="viewRegistration">查看退住申请</el-button>
          </el-form-item>
        </el-form>
  
        <div class="table-title">
          <h3>客户信息</h3>
        </div>
        <!-- 表格区域 -->
        <el-table :data="tableData" border stripe style="width: 100%;">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="name" label="客户姓名" width="100" />
          <el-table-column prop="age" label="年龄" width="140" />
          <el-table-column prop="gender" label="性别" width="120" 
          :formatter="r => r.gender===0?'男':'女'"/>
		  <el-table-column prop="roomNumber" label="房间号" width="60" />
          <el-table-column prop="bedNumber" label="床号" />
          <el-table-column prop="careLevelName" label="护理级别" width="160" />
          <el-table-column fixed="right" label="操作" width="160">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="add(row)">添加退住申请</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页区域 -->
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @current-change="loadData"
          @size-change="loadData"
        />
      </el-card>
  
      <!-- 抽屉表单 -->
      <el-drawer v-model="drawerVisible" :title="drawerTitle" size="40%">
        <el-form :model="formData" label-width="100px">
          <el-form-item label="客户姓名">
            <el-input v-model="formData.name" />
          </el-form-item>
          <el-form-item label="退住时间">
            <el-date-picker v-model="formData.checkOutTime" type="date" />
          </el-form-item>
          <el-form-item label="退住类型">
            <el-radio-group v-model="formData.checkOutType">
              <el-radio :value="0">正常退住</el-radio>
              <el-radio :value="1">死亡退住</el-radio>
              <el-radio :value="2">保留床位</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="退住原因">
            <el-input v-model="formData.checkOutReason" />
          </el-form-item>
          <el-form-item label="审批状态">
            <el-radio-group v-model="formData.approveStatus">
              <el-radio :value="0">已提交</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">{{ drawerTitle }}</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, watch, inject } from 'vue';
  import dayjs from 'dayjs';
  import { ElMessage } from 'element-plus';
  import qs from 'qs';
  import { jwtDecode } from 'jwt-decode'
  
  // 注入 axios
  const axios = inject('axios');
  
  // 抽屉状态与标题
  const drawerVisible = ref(false);
  const drawerTitle = ref('退住登记');
  const nurseId=ref('');

  const init = ()=>{
      let token=sessionStorage.getItem('token');
      const payload = jwtDecode(token);
      const user = JSON.parse(payload.mobileJson)
      nurseId.value=user.id;
      console.log(nurseId.value);
  }
  init();

  import { useRouter } from 'vue-router'

  const router = useRouter()

  function viewRegistration() {
  router.push({
    path: '/CheckOutRecord',
    query: { nurseId: nurseId }
  })
}
  
  // 表单与搜索模型
  const formData = reactive({
    id: null,
    customerId: null,
    name:'',
    checkOutTime: '',
    checkOutType: 0,
    checkOutReason: '',
    approveStatus: 0,
    operatorUserId: null,
    approveTime: ''
  });
  const searchForm = reactive({ name: '' });
  
  // 表格与分页
  const tableData = ref([]);
  const currentPage = ref(1);
  const pageSize = ref(10);
  const total = ref(0);
  
  // 加载列表
  const loadData = () => {
    axios.post('CheckOutRegistrationController/searchClient',qs.stringify({
      cur: currentPage.value,
      number: pageSize.value,
      clientName: searchForm.name,
      healthManagerId: nurseId.value
    })).then(response => {
      const rb = response.data;
      if (rb.status === 200) {
        tableData.value = rb.data;
        total.value = rb.total;
      } else {
        ElMessage.error('加载失败: ' + rb.msg);
      }
    });
  };
  watch([currentPage, pageSize], loadData);
  loadData();
  
  // 查询
  const searchData = () => { currentPage.value = 1; loadData(); };
  
  const add = (row) => {
    Object.assign(formData, {
    id: null,
    customerId: row.id,
    name:row.name,
    checkOutTime: '',
    checkOutType: 0,
    checkOutReason: '',
    approveStatus: 0,
    operatorUserId: null,
    approveTime: ''
    });
    drawerTitle.value = '添加退住申请';
    drawerVisible.value = true;
  };
  
  // 提交表单（新增或修改）
  const submitForm = () => {
    formData.checkOutTime = dayjs(formData.checkOutTime).format('YYYY-MM-DD')

    const payload = { ...formData };
        // 不提交空的日期字段
        if (!payload.checkOutTime)         delete payload.checkOutTime;
  	    if (!payload.approveTime)     delete payload.approveTime;
          // 同样也 delete payload.customerName 等展示字段……
          delete payload.customerName;
    const url = 'CheckOutRegistrationController/checkOutRegister';
    axios.post(url, qs.stringify(payload)).then(response => {
      const rb = response.data;
      if (rb.status === 200) {
        ElMessage.success(`${drawerTitle.value}成功`);
        drawerVisible.value = false;
        loadData();
      } else {
        ElMessage.error(rb.message);
      }
    });
  };
  

  </script>
  
  <style scoped>
  .el-pagination { margin-top: 20px; }
  .table-title { background: #f5f5f5; padding: 8px; margin: 10px 0; }
  </style>